/**
 * @program: LeetCode
 * @description: LeetCode :
 * @author: WXY
 * @create: 2023-01-03 10:22
 * @Version 1.0
 **/
public class offer_seventeen2_maxPathSum {
    public static int maxPathSum(TreeNode root) {

        Info ans = process(root);
        return ans.maxSum;
    }

    private static Info process(TreeNode node) {
        if (node == null) {
            return null;
        }


        Info leftInfo = process(node.left);
        Info rightInfo = process(node.right);
        //无关当前节点的最大和
        int leftMaxSum = leftInfo == null ? Integer.MIN_VALUE : leftInfo.maxSum;
        int rightMaxSum = rightInfo == null ? Integer.MIN_VALUE : rightInfo.maxSum;
        int curNodeMaxSum = Math.max(leftMaxSum, rightMaxSum);
        //有点当前节点的最大和
        int curNodeToLeafSum = node.val;
        int curLeftNodeToLeafSum = curNodeToLeafSum + (leftInfo == null ? 0 : leftInfo.curNodeToLeafSum);
        int curRightNodeTolearSum = curNodeToLeafSum + (rightInfo == null ? 0 : rightInfo.curNodeToLeafSum);
        curNodeToLeafSum = Math.max(curNodeToLeafSum, Math.max(curLeftNodeToLeafSum, curRightNodeTolearSum));

        int sum_1 = curLeftNodeToLeafSum + curRightNodeTolearSum - node.val;
        int sum_2 = curLeftNodeToLeafSum;
        int sum_3 = curRightNodeTolearSum;
        int sum_4 = node.val;
        int finalSum = Math.max(sum_1, Math.max(sum_2, Math.max(sum_3, sum_4)));
        curNodeMaxSum = Math.max(curNodeMaxSum, finalSum);
        return new Info(curNodeToLeafSum, curNodeMaxSum);

    }

    public static class Info {
        public int curNodeToLeafSum;
        public int maxSum;

        public Info(int curNodeToLeafSum, int maxSum) {
            this.curNodeToLeafSum = curNodeToLeafSum;
            this.maxSum = maxSum;
        }
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
